package com.ruoyi.system.utils;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SM4;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.config.ApiConfig;
import com.ruoyi.system.domain.SysPhoneRsp;
import com.ruoyi.system.domain.SystemFile;
import com.ruoyi.system.service.ISysFileService;
import com.ruoyi.system.service.ISysPhoneRspService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 任务
 * @author: wangp
 * @date: 2025年03月12日 14:21
 */

public class ParametricTask implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(ParametricTask.class);


    private final String requestId;
    private final Long fileId;

    /**
    * @Description: 通过构造函数接收参数
    * @author: wangp
    * @date: 2025/3/12 14:22
    * @param requestId:
    * @Return:
    */
    public ParametricTask(String requestId, Long fileId) {
        this.requestId = requestId;
        this.fileId = fileId;
    }

    @Override
    public void run() {
        String s = IdUtils.fastSimpleUUID();
        ApiConfig apiConfig = SpringUtils.getBean("apiConfig");
        JSONObject head = HttpApi.generateHead(s, apiConfig.getSecretid(), apiConfig.getSecretkey());
        JSONObject request = JSONObject.of("requestId", requestId);
        String batchResponse = HttpApi.sendCommonSSLApi("batch/task", apiConfig.getUrl(), "application/json", head, request);

        log.info("batch/task -> requestId:{} fileId:{} batchResponse:{}", requestId, fileId, batchResponse);
        JSONObject taskResult = JSONObject.parseObject(batchResponse);
        String taskStatus = taskResult.getString("taskStatus");

        // 更新任务状态
        ISysFileService sysFileService = SpringUtils.getBean("sysFileService");
        SystemFile systemFile = new SystemFile();
        systemFile.setId(fileId);
        systemFile.setTaskStatus(taskStatus);
        // 1:执行中 2:查询完成 -1:执行失败 0:无效的任务id 3:排队中
        switch (taskStatus) {
            case "1":
            case "3":
                // 30分钟后查询
                TaskScheduler taskScheduler = SpringUtils.getBean("taskScheduler");
                // 当前排队任务100个，前面还有20个任务待处理。 可基于排队位置优化执行时间
                String responseMsg = taskResult.getString("responseMsg");

                log.info("responseMsg:{}", responseMsg);
                int delay = "1".equals(taskStatus) ? 30 : 60;
                taskScheduler.submit(new ParametricTask(requestId, fileId), delay, TimeUnit.MINUTES);
                break;
            case "2":
                // 下载文件存储并记录
                String resultFiles = taskResult.getString("taskResult");
                JSONArray rfs = taskResult.getJSONArray("taskResult");

                List<String> paths = new ArrayList<>();
                log.info("resultFiles:{}", resultFiles);
                String destDir = RuoYiConfig.getUploadPath() + File.separator + "zipF" + File.separator + fileId;
                for (int i = 0; i < rfs.size(); i++) {
                    JSONArray jsonArray = rfs.getJSONObject(i).getJSONArray("fileIds");
                    for (int j = 0; j < jsonArray.size(); j++) {
                        String id = jsonArray.getString(j);

                        JSONObject headF = HttpApi.generateHead(s, apiConfig.getSecretid(), apiConfig.getSecretkey());
                        JSONObject requestF = JSONObject.of("requestId", requestId, "fileId", id);
                        String savePath = RuoYiConfig.getUploadPath() + File.separator + "zipF" + File.separator + fileId + File.separator + i + "_" + j + ".zip";

                        String batchResponseF = HttpApi.saveFileSSLApi("batch/download", apiConfig.getUrl(), "application/json", headF, requestF, savePath);
                        log.info("batchResponseF:{}", batchResponseF);
                        CompressUtil.unzip(savePath, destDir);
                        paths.add(destDir);

                    }
                }
                log.info("paths:{}", paths);
                updatePhoneRsp(apiConfig.getSecretkey(), destDir);
//                systemFile.setResultPath(String.join(";", paths));
                // 读取文件信息解密存储

                break;
            case "-1":
            case "0":
                // 任务执行失败
                break;
            default:
                // 错误任务状态
                break;
        }
        sysFileService.updateSysFile(systemFile);

    }


    public static void updatePhoneRsp(String secretkey, String destDir) {
        Path dir = Paths.get(destDir);

        ISysPhoneRspService sysPhoneRspService = SpringUtils.getBean("sysPhoneRspService");
        try (Stream<Path> txts = Files.list(dir)) {
            // 1. 过滤出所有.txt文件
            List<SysPhoneRsp> allTextContents = txts
                    .filter(path -> ReadTxtFiles.isTxtFile(path)) // 过滤扩展名为.txt的文件
                    .flatMap(path -> ReadTxtFiles.readFileContent(path)) // 读取每个文件的内容
                    .map(line -> line.trim().split("\\|"))           // 分割每行数据
                    .filter(parts -> parts.length == 3)              // 过滤有效数据
                    .map(parts -> {
                            SysPhoneRsp sysPhoneRsp = new SysPhoneRsp();
                            sysPhoneRsp.setEmpowerNo(parts[0].trim());
                            String responseStatus = parts[1].trim();
                            String response = parts[2].trim();
                            sysPhoneRsp.setResponseStatus(responseStatus);
                            if ("0000".equals(responseStatus)) {
                                String decrypt = null;
                                try {
                                    decrypt = SM4.decrypt(response, secretkey);
                                } catch (Exception e) {
                                    throw new UtilException("解密失败", e);
                                }
                                JSONObject jsonObject = JSONObject.parseObject(decrypt);
                                String gfyy_score = jsonObject.getString("gfyy_score");
                                String fdcyxjz_score = jsonObject.getString("fdcyxjz_score");
                                log.info("decrypt:{} gfyy_score:{} fdcyxjz_score:{}", decrypt, gfyy_score, fdcyxjz_score);
                                sysPhoneRsp.setResponse(decrypt);
                                sysPhoneRsp.setScore(StringUtils.firstNonBlank(gfyy_score, fdcyxjz_score));
                            } else {
                                sysPhoneRsp.setResponse(response);
                            }
                            return sysPhoneRsp;
                        }
                    ).collect(Collectors.toList()); // 收集所有内容到列表

            // 打印结果
            log.info("sysPhoneRsps:{}", allTextContents);
            // 添加日志记录以检查 batchUpdateSysPhoneRsps 的执行情况
            allTextContents.forEach(sysPhoneRspService::updateSysPhoneRsp);
        } catch (IOException e) {
            log.error("读取文件夹失败: ", e);
        }
    }

}